package com.es.db.indexdb.dao.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.es.db.indexdb.dao.BaseDao;
import com.es.db.indexdb.dao.SellAmountDao;

public class SellAmountDaoImpl extends BaseDao implements SellAmountDao{

	@Autowired
	private JdbcTemplate indexDBTemplate;
	
	@Autowired
	private DataSourceTransactionManager indexDBTransactionManager;
	public int update(int product, int amount) {
		String sql = "update t_sellamount set amount=(amount-?)  where productid = ? and amount >=?";
		int row = 0;
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = indexDBTransactionManager.getTransaction(def);
		boolean flag = false;
		try {
			//Object[] params = {product};
			//只支持基本数据类型的映射
			//Integer oldmount = getIndexDBTemplate().queryForObject("select amount from t_sellamount where productid=?", params, Integer.class);
			//amount = oldmount-amount;
			row =  indexDBTemplate.update(sql, amount,product, amount);
			if (row > 0) {
				flag= true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (flag) {
				indexDBTransactionManager.commit(status);
			}else {
				indexDBTransactionManager.rollback(status);
			}
			
		}
		
		return row;
	}

}
